#include "Menu.h"
using namespace std;
using namespace Course;

Menu::Menu()
{
	xpos = 0;
	ypos = 0;
	ptrPos = 0;
}

Menu::Menu(int xpos, int ypos, vector<string> menuItems)
{
	for (int i = 0; i < menuItems.size(); i++){
		this->menuItems.push_back(menuItems[i]);
	}
	this->xpos = xpos;
	this->ypos = ypos;
	ptrPos = 0;
}

Menu::~Menu()
{
}

int Menu::runMenu()
{
	drawMenu();
	inputHandler();
	return ptrPos;
}

void Menu::drawMenu()
{
	Console::clrscr();
	for (int i = 0; i < menuItems.size(); i++){
		Console::gotoxy(xpos, ypos + i);
		cout << menuItems[i];
	}
	pointerHandler(0);
}

void Menu::pointerHandler(int change)
{
	Console::gotoxy(xpos + menuItems[ptrPos].length(), ypos + ptrPos);
	cout << "    "; //clear the cursor
	if (change > 0 && ptrPos >= (menuItems.size() - 1)){
		ptrPos = 0;
	}
	else if (change < 0 && ptrPos <= 0){
		ptrPos = menuItems.size() - 1;
	}
	else{
		ptrPos += change;
	}

	Console::gotoxy(xpos + menuItems[ptrPos].length(), ypos + ptrPos);
	cout << " <==";
}

void Menu::inputHandler()
{
	Console::setcursor(0, 20);
	bool noSelection = true;
	while (noSelection){
		switch (char input = _getch()){
		//Move up
		case 72:
			pointerHandler(-1); break;
		//Move down
		case 80:
			pointerHandler(+1); break;
		//Return
		case 13:
			noSelection = false; break;
		default:
			break;
		};
	}
	Console::setcursor(1, 20);
}